<?php

namespace humhub\modules\api\cccstream;

use Yii;

class Comments extends \yii\web\Controller
{

    /**
     * Return Object CommentsList
     */
    public static function getLists($object){
        $modelName = $object->content->object_model;
        $modelId = $object->content->object_id;

        // Count all Comments
        $commentCount = \humhub\modules\comment\models\Comment::GetCommentCount($modelName, $modelId);
        $comments = \humhub\modules\comment\models\Comment::GetCommentsLimited($modelName, $modelId, 2);

        $isLimited = ($commentCount > 2);

        $output = array();
        foreach($comments AS $comment){
            $user['displayname'] = $comment->user->displayName;
            $user['guid'] = $comment->user->guid;
            $user['image'] = $comment->user->getProfileImage()->getUrl();
            $user['g_name'] = $comment->user->g_name;
            $user['g_url'] = $comment->user->g_url;



            $_cm = $comment->attributes;
            $cm['id'] = $_cm['id'];
            $cm['message'] = $_cm['message'];
            $cm['object_id'] = $_cm['object_id'];
            $cm['created_at'] = $_cm['created_at'];
            $cm['updated_at'] = $_cm['updated_at'];
            $cm['user'] = $user;
            //$cm['canWrite'] = $comment->canWrite();
            //$cm['canDelete'] = $comment->canDelete();

            //Files
            $cm['files'] = [];
            $cm['image'] = [];
            if ($comment->isNewRecord && $comment->getRelation('content', false) !== null) {
                $files = \humhub\modules\file\models\File::findAll(['guid' => array_map('trim', explode(',', $comment->content->attachFileGuidsAfterSave))]);
            } else {
                $files = \humhub\modules\file\models\File::getFilesOfObject($comment);
            }
            foreach ($files as $file){
                if ($file->getMimeBaseType() == "image"){
                    $cm['image'][] = $file->getPreviewImageUrl(200, 200);
                }
            }
            foreach ($files as $file){
                if ($file->getMimeBaseType() == "image")
                    continue;
                $f['url'] = $file->getUrl();
                $f['name'] = $file->file_name;
                $f['size'] = $file->size; //Yii::$app->formatter->asSize($file->size);
                $cm['files'][] = $f;
            }

            $output[] = $cm;
        }

        //return $output;
        return array(
            'list'  => $output,
            'count' => $commentCount,
        );
    }
}
?>
